//
//  CatVoiceVController.m
//  DoorBell
//
//  Created by eques on 2024/2/23.
//  Copyright © 2024 eques. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "CatVoiceVController.h"
#import "CatRecordView.h"
#import "CatVoiceCell.h"
#import "EncoderG711.h"
@interface CatVoiceVController ()<AVAudioRecorderDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIImageView *noMp3Imageview;
@property(nonatomic,strong)UILabel *noMp3Label;

@property(nonatomic,strong)CatRecordView *recordView;
@property(nonatomic,strong)AVAudioRecorder *audioRecorder;
@property(nonatomic,strong)NSString* recordUrl;
@property(nonatomic,strong)AVAudioSession * audioSession;
@property(nonatomic,strong)AVAudioPlayer *audioPlayer; //播放器
@property(nonatomic,assign)int recordTime;
@property(nonatomic,assign)int second;
@property(nonatomic,assign)int minute;
@property(nonatomic,strong)NSTimer* timer;
@property(nonatomic,copy)NSString *mp3Path;
@property(nonatomic,copy)NSString *file_name;
@property(nonatomic,strong)UITableView *mp3Tableview;
@property(nonatomic,strong)NSMutableArray *mp3Array;


@property(nonatomic,assign)BOOL isplaying;
@property(nonatomic,assign)BOOL isrecording;

@property(nonatomic,strong)NSMutableArray *sinXViews;

@property(nonatomic,strong)EncoderG711 *encoderPcmToG711; //pcm转g711a对象
@property(nonatomic,strong)NSIndexPath *indexPath;

@end

@implementation CatVoiceVController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    
    self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
   
    self.indexPath = [NSIndexPath indexPathForRow:0 inSection:list.voice_index];
   
    self.encoderPcmToG711 = [[EncoderG711 alloc]init];
    self.mp3Array =  nil;
    
  
   
    [self get_data];
    
   if(self.mp3Array.count > 0){
       
       if(_noMp3Imageview){
         [_noMp3Imageview removeFromSuperview];
          _noMp3Imageview = nil;
       }
       
       if(_noMp3Label){
         [_noMp3Label removeFromSuperview];
          _noMp3Label = nil;
       }
       [self.mp3Tableview reloadData];
       
   }else{
       self.noMp3Imageview.image = [UIImage imageNamed:@"cat_msg_none"];
       self.noMp3Label.text = NSLocalizedString(@"点击话筒按钮可录制最长15s的语音，每次出粮就播放最新的一条录制的语音",nil);
       self.encoderPcmToG711 = [[EncoderG711 alloc]init];
   }
 
    [self record_setting];
     self.recordView.backgroundColor = [UIColor whiteColor];
    [self.recordView.recordButton setImage:[UIImage imageNamed:@"sd78_voice"] forState:UIControlStateNormal];
    NSString *str =   NSLocalizedString(@"点击添加录音",nil);
     self.recordView.deslabel.text =  str;
    
     __weak CatVoiceVController *weakself = self;
     self.recordView.recordBlock = ^{
         
         //在录音中 再点击录音，返回
         if(weakself.isrecording){
             return;
         }
          weakself.recordView.deslabel.text =  NSLocalizedString(@"录制中",nil);;
          weakself.recordView.timelabel.text =@"00:00";
         [weakself.recordView.stopButton setImage:[UIImage imageNamed:@"sd78_cancel"] forState:UIControlStateNormal];
         [weakself.recordView.postButton setImage:[UIImage imageNamed:@"sd78_done"] forState:UIControlStateNormal];
         [weakself start_record];
         
     };
    
    self.recordView.stopBlock = ^{
        [weakself setPalyCellRecord:NO];
        [weakself.recordView.stopButton removeFromSuperview];
         weakself.recordView.stopButton = nil;
        [weakself.recordView.postButton removeFromSuperview];
         weakself.recordView.postButton = nil;
        
        weakself.recordTime = 0;
       [weakself.audioRecorder stop];
       [[AVAudioSession sharedInstance] setActive:NO error:nil];
       [weakself.timer invalidate];
       [weakself.recordView.timelabel removeFromSuperview];
        weakself.recordView.timelabel = nil;
        weakself.recordView.deslabel.text = str;
       [weakself.recordView.stopButton removeFromSuperview];
        weakself.recordView.stopButton = nil;
       [weakself.recordView.postButton removeFromSuperview];
        weakself.recordView.postButton = nil;
        
    };
    
    self.recordView.postBlock = ^{
        [weakself.recordView.timelabel removeFromSuperview];
        weakself.recordView.timelabel = nil;
        [weakself.recordView.stopButton removeFromSuperview];
         weakself.recordView.stopButton = nil;
        [weakself.recordView.postButton removeFromSuperview];
         weakself.recordView.postButton = nil;
         weakself.recordView.deslabel.text = str;
        [weakself setPalyCellRecord:NO];
        [weakself.audioRecorder stop];
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        [weakself.timer invalidate];
         weakself.timer = nil;
        
        
        [weakself upload_g711a];
     
    };
    
}

- (void)get_data
{
    [self.mp3Array removeAllObjects];
    [SVProgressHUD show];

    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat_feed" ofType:@"mp3"];
    CatVoiceModel *info = [[CatVoiceModel alloc]init];
    info.bid =  self.bid;
    info.cell_type = 1;
    info.voice_type = 1;
    info.file_name_value = @"cat_feed";
    info.durtation = 2;
    info.file_name = NSLocalizedString(@"使用默认语音",nil);
    info.timeinterval = [[NSDate date] timeIntervalSince1970];
    info.file_path = path;
    info.userName = [Tooles getuserToken];
    info.durtation_str = @"00:02";

    [self.mp3Array addObject:info];
    
    //获取服务器上的录音资源
    NSURL *url = [YKBusinessFramework get_g711a:_bid version:0];

    [AFNHTTPSRequest httpsRequestWithUrl:url errorHint:^(id errorData) {
        NSLog(@"data---%@",errorData);
        [SVProgressHUD dismiss];
        
    } result:^(id data) {
        NSLog(@"data---%@",data);
    
         /*
         {
           "reason" : "success",
           "data" : {
             "version" : 7,
             "fileId" : "AmYAAAABHABwdWJsaWMvcGV0L2s0bXpTOFhjeWVwVS5nNzExAAAAAAAC"
           },
           "code" : 0
         }
         */
        [SVProgressHUD dismiss];
        if ([[data objectForKey:@"code"] intValue] == 0) {
            NSDictionary *dict = [data objectForKey:@"data"];
            int version = [[dict objectForKey:@"version"] intValue];
            self.version = version;
            
            if (self.version > 0) {
            
                CatVoiceModel *info = [[CatVoiceModel alloc]init];
                info.bid =  self.bid;
                info.cell_type = 1;
                info.voice_type = 1;
                info.file_name_value = @"cat_feed";
                info.durtation = 2;
                info.file_name = NSLocalizedString(@"自定义语音",nil);
                info.timeinterval = [[NSDate date] timeIntervalSince1970];
                info.file_path = path;
                info.userName = [Tooles getuserToken];
                [self.mp3Array addObject:info];
            }
        }
        [self.mp3Tableview reloadData];
    }];
    

   
}

- (void)setup
{
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame = CGRectMake(0,0,80,60);
    backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
    backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
   [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
   [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
   [backbtn setImage: [UIImage imageNamed:@"button_back_lightgray_arrow"] forState:UIControlStateNormal];
   [backbtn addTarget:self action:@selector(selectLeftAction) forControlEvents:UIControlEventTouchUpInside];
   [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5 imagePositionBlock:^(UIButton *button){
   }];
   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
  
   UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.frame = CGRectMake(0, 0, 80,44);
    settingBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
    NSString *str =  NSLocalizedString(@"添加语音",nil);
   [settingBtn setTitle:str forState:UIControlStateNormal];
   [settingBtn setTitleColor:[HexChangeRGB colorWithHexString:@"#754c24"] forState:UIControlStateNormal];
    self.navigationItem.titleView = settingBtn;
}

- (void)selectLeftAction
{
    if (self.isplaying) {
        for (CatVoiceCell *item in self.mp3Tableview.visibleCells) {
            [item stopPlay];
        }
    }
    
    if(self.isrecording){
        self.recordTime = 0;
       [self.audioRecorder stop];
       [[AVAudioSession sharedInstance] setActive:NO error:nil];
       [self.timer invalidate];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(@available(iOS 15.0,*)){
        UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
        apperance.backgroundColor = [UIColor whiteColor];//设置背景色
        self.navigationController.navigationBar.standardAppearance = apperance;
        self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
}


- (void)upload_g711a
{
    [SVProgressHUD show];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSMutableDictionary *dcit = [NSMutableDictionary dictionary];
        [dcit setObject:[Tooles get_token] forKey:@"token"];
        [dcit setObject:[Tooles get_uid] forKey:@"uid"];
        [dcit setObject:self.bid forKey:@"deviceId"];
        [dcit setObject:@(self.recordTime) forKey:@"duration"];
       
        NSData *data;
        NSURL *url;
        NSString *file_name;
        NSData *data1 = [[NSData alloc]initWithContentsOfFile:self.recordUrl];
        data = [self encodeG711:data1];
        url = [YKBusinessFramework upload_g711a];
        file_name = @"001.g711";
        
        [AFNHTTPSRequest httpsUploadDocumentWithUrl:url parameters:dcit documentData:data name:@"file" fileName:file_name mimeType:@"audio/mpeg" errorHint:^(id errorData) {
            
            [SVProgressHUD dismiss];
            NSLog(@"上传录音失败--->%@",errorData);
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置失败", nil) duration:1.0];
            });
        } result:^(id data) {
        
            
            NSLog(@"上传录音--->%@",data);
            [SVProgressHUD dismiss];
            if ([[data objectForKey:@"code"] intValue] == 0) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *str =  NSLocalizedString(@"添加录音成功", nil);
                    [SVProgressHUD showSuccessWithStatus:str duration:1.0];
                     self.mp3Path = nil;
                    
                    [self get_data];
                });
            }else{
                self.recordTime = 0;
                self.file_name = nil;
                self.mp3Path = nil;
            }
        }];
    });
}


- (void)record_setting
{
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）, 采样率必须要设为11025才能使转化成mp3格式后不会失真
    [recordSetting setValue:[NSNumber numberWithFloat:8000] forKey:AVSampleRateKey];
    //录音通道数  1 或 2 ，要转换成mp3格式必须为双通道
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    //存储录音文件 (临时文件夹)
    self.recordUrl = [NSTemporaryDirectory() stringByAppendingString:@"selfRecord.caf"]; ;
    
    //初始化
    self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:self.recordUrl] settings:recordSetting error:nil];
    //开启音量检测
     self.audioRecorder.meteringEnabled = YES;
     self.audioRecorder.delegate = self;
    [self.audioRecorder updateMeters];
    
    
}

- (void)start_record
{
   
    
    if(self.isplaying){
      [self stopPalyingCell];
       self.isplaying = NO;
    }
    [self setPalyCellRecord:YES];
    
    self.audioSession = [AVAudioSession sharedInstance];
    
    if (![self.audioRecorder isRecording]) {
        [self.audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];//设置类别,表示该应用同时支持播放和录音
        [self.audioSession setActive:YES error:nil];//启动音频会话管理,此时会阻断后台音乐的播放.
        
        [self.audioRecorder prepareToRecord];
        [self.audioRecorder peakPowerForChannel:0.0];
        [self.audioRecorder record];
         self.recordTime = 0;
        
        [self recordTimeStart];
        
    }
    else{
        [self setPalyCellRecord:NO];
        [self.audioRecorder stop];                          //录音停止
        [self.audioSession setActive:NO error:nil];         //一定要在录音停止以后再关闭音频会话管理（否则会报错），此时会延续后台音乐播放
        [self.timer invalidate];                            //timer失效
        [self.recordView.timelabel removeFromSuperview];
        NSString *str =  NSLocalizedString(@"点击添加录音",nil);
         self.recordView.deslabel.text = str;
        
        [self.recordView.stopButton removeFromSuperview];
         self.recordView.stopButton = nil;
        [self.recordView.postButton removeFromSuperview];
         self.recordView.postButton = nil;
    }
}


- (void)recordTimeStart {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTick) userInfo:nil repeats:YES];
}

- (void)recordTimeTick {
    self.recordTime += 1;
    self.recordView.deslabel.text = NSLocalizedString(@"录制中",nil);
    if (self.recordTime == 15) {
        [self setPalyCellRecord:NO];
        [self.audioRecorder stop];
        [[AVAudioSession sharedInstance] setActive:NO error:nil];
        [self.timer invalidate];
         self.timer = nil;
        [self.recordView.timelabel removeFromSuperview];
         self.recordView.timelabel = nil;
         NSString *str = NSLocalizedString(@"点击添加录音",nil);
         self.recordView.deslabel.text = str;
        [self.recordView.stopButton removeFromSuperview];
         self.recordView.stopButton = nil;
        [self.recordView.postButton removeFromSuperview];
         self.recordView.postButton = nil;
            
        [self upload_g711a];
        return;
    }
    [self updateAudioRecordTime];
}

- (void)updateAudioRecordTime {
    self.minute = self.recordTime/60.0;
    self.second = self.recordTime-self.minute*60;
    self.recordView.timelabel.text = [NSString stringWithFormat:@"%02d:%02d",self.minute,self.second];

}


- (CatRecordView*)recordView
{
    if(!_recordView){
         _recordView = [[CatRecordView alloc]init];
         _recordView.layer.cornerRadius = 20;
         _recordView.layer.borderWidth = 1.0;
         _recordView.layer.borderColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"].CGColor;
         _recordView.layer.masksToBounds = YES;
        [self.view addSubview:_recordView];
        [_recordView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth);
            make.height.mas_equalTo(220);
            make.bottom.equalTo(self.view.mas_bottom).offset(20);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
    }
    return _recordView;
}


- (UITableView*)mp3Tableview
{
    if (!_mp3Tableview) {
         _mp3Tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         _mp3Tableview.rowHeight = 60;
        [_mp3Tableview registerClass:[CatVoiceCell class] forCellReuseIdentifier:@"CatVoiceCell"];
         _mp3Tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
         _mp3Tableview.delegate = self;
         _mp3Tableview.dataSource = self;
        [self.view addSubview:_mp3Tableview];
        [_mp3Tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-200);
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
        }];
    }
    return _mp3Tableview;
}


#pragma mark 将pcm数据转为g711a
- (NSData *)encodeG711:(NSData *)data {
    
    if(!self.encoderPcmToG711){
       return nil;
    }
    NSUInteger datalength = [data length];
    Byte *byteData = (Byte *)[data bytes];
    short *pPcm = (short *)byteData;
    int outlen = 0;
    int len = (int)datalength/2;
    Byte *G711Buff = (Byte *)malloc(len);
    memset(G711Buff,0,len);
    int i;
    for (i=0; i<len; i++) {
        G711Buff[i] = [self.encoderPcmToG711 linear2alaw:pPcm[i]];
    }
    outlen = i;
    Byte *sendbuff = (Byte *)G711Buff;
    NSData *sendData = [[NSData alloc] initWithBytes:sendbuff length:len];
    free(G711Buff);
    return sendData;
}





// 获取当前时间
- (NSString *)currentDateStr{

     NSDate *date = [NSDate date];
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateFormat:@"YYYY.MM.dd HH:mm:ss"];
     NSString *dateStringInTwentyHours = [dateFormatter stringFromDate:date];
    return dateStringInTwentyHours;
}


- (NSMutableArray*)mp3Array
{
    if(!_mp3Array){
        _mp3Array = [NSMutableArray array];
    }
    return _mp3Array;
}


- (UIImageView*)noMp3Imageview
{
    if (!_noMp3Imageview) {
         _noMp3Imageview = [[UIImageView alloc]init];
        [self.view addSubview:_noMp3Imageview];
        [_noMp3Imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(142);
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.mas_equalTo(146);
            make.height.mas_equalTo(158);
        }];
        
    }
    return _noMp3Imageview;
}

- (UILabel*)noMp3Label
{
    if (!_noMp3Label) {
          _noMp3Label = [[UILabel alloc]init];
         [self.view addSubview:_noMp3Label];
          _noMp3Label.textColor = [HexChangeRGB colorWithHexString:@"#999999"];
          _noMp3Label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
          _noMp3Label.numberOfLines = 0;
         [_noMp3Label sizeToFit];
         [_noMp3Label mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.noMp3Imageview.mas_bottom).offset(35);
            make.left.equalTo(self.view.mas_left).offset(17);
            make.right.equalTo(self.view.mas_right).offset(-17);
         }];
    }
       
    return _noMp3Label;
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.mp3Array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CatVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatVoiceCell" forIndexPath:indexPath];
    cell.bid = self.bid;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.mp3Array[indexPath.section];
    cell.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    __weak CatVoiceVController *tempSelf = self;
    __weak CatVoiceCell *tempCell = cell;
    if (self.indexPath == indexPath) {
        cell.selectedImage.image = [UIImage imageNamed:@"select_icon"];
        
    }else{
        cell.selectedImage.image = [UIImage imageNamed:@"icon_check_alpha"];
    }
    if (cell.isPlaying){
       [cell stopPlay];
    };
    
    cell.playBlock = ^(BOOL isPlay) {
        
        if(isPlay){
            for (CatVoiceCell *item in tempSelf.mp3Tableview.visibleCells) {
                if (item != tempCell && item.isPlaying){
                    [item stopPlay];
                };
            }
        }
        self.isplaying = isPlay;
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
        [SVProgressHUD show];
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       [dict setValue:[NSString stringWithFormat:@"%ld",(long)indexPath.section] forKey:@"voice_index"];
       [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
           [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
       }deleteDic:dict isFavorite:YES result:^(id data) {
              NSLog(@"show_open_lock_button data-->%@",data);
             [SVProgressHUD dismiss];
             if ([[data objectForKey:@"code"] intValue] == 0)
             {
                 [SVProgressHUD dismiss];
                 if (list.status != 0) {
                     
                      NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                     [YKBusinessFramework equesSendData:Str];
                 }
                 
                 FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                 list.voice_index = (int)indexPath.section;
                [list bg_saveOrUpdate];
                
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                     self.indexPath = indexPath;
                    [self.mp3Tableview reloadData];
                 });
                
             }else{
            
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                     [self.mp3Tableview reloadData];
                 });
             }
       }];
    

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        return 20;
    }else{
        return 10;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    return view;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    return view;
}


#pragma mark 关闭其他正在播放的cell
- (void)stopPalyingCell{
    //循环显示的cell
    for (CatVoiceCell *item in self.mp3Tableview.visibleCells) {
        if (item.isPlaying) {
            [item stopPlay];
        }
    }
}

#pragma mark 录制时，设置cell正在录制的标记
- (void)setPalyCellRecord:(BOOL)isRecording{
    self.isrecording = isRecording;
    //循环显示的cell
    for (CatVoiceCell *item in self.mp3Tableview.visibleCells) {
         item.isRecording = isRecording;
    }
}



 


@end
